<?php

namespace App\CommandModel;

use App\Helpers\Helpers;
use App\Model\OrderBonus;
use App\Model\UserPoint;
use App\User;
use Illuminate\Support\Facades\DB;

class OrderBonuses
{
    public $userIds = [];

    public function run()
    {
        //发送
        $model = (new OrderBonus())->whereRaw('status is null or status="FAIL"')->where('auto_pay','=',1)
            ->whereNull('payment_time');
        $model->chunk(50,function ($items){
            foreach ($items as $item){
                $this->userIds = array_push($this->userIds,$item->bonus_user_id);
                $this->send_request($item);
            }
        });

        //查询
        $model = (new OrderBonus())->whereIn('status',['FAIL','PROCESSING'])->where('auto_pay','=',1)
            ->whereNull('payment_time');
        $model->chunk(50,function ($items){
            foreach ($items as $item){
                $this->userIds = array_push($this->userIds,$item->bonus_user_id);
                $this->query_request($item);
            }
        });

        //更新用户积分
        $userIds = array_unique($this->userIds);

        if (count($userIds)>0){
            foreach ($userIds as $id){
                User::updateUserPoint($id);
            }
        }

        return true;
    }

    public function send_request($item)
    {
        $payment = app('wechat.payment');
        $result = $payment->transfer->toBalance([
            'partner_trade_no' => $item->partner_trade_no,
            'openid' => $item->openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => '', // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => 100*$item->amount, // 企业付款金额，单位为分
            'desc' => $item->desc, // 企业付款操作说明信息。必填
        ]);

        Helpers::log('[send] out_trade_no:'.$item->out_trade_no.' result:'.json_encode($result),'bonuses');

        $item->send_count +=1;
        $item->last_send_time =date('Y-m-d H:i:s');
        $item->save();

        if (!$result || ($result&&$result['return_code'] != "SUCCESS")) return false;

        if ($result['result_code'] == 'SUCCESS'){
            $item->payment_no = $result['payment_no'];
            $item->payment_time = $result['payment_time'];
            $item->transfer_time = $item->payment_time;
            $item->status = 'SUCCESS';
            $item->transfer_time = date('Y-m-d H:i:s');
            $item->save();
        }else{
            $this->query_request($item);
        }

        $result = DB::table('order_bonuses')->select('id','bonus_user_id','amount','desc','status')
            ->where('id','=',$item->id)->first();

        if ($result && $result->status == "SUCCESS") {
            UserPoint::createOneRecord($result->bonus_user_id,-1*$result->amount,'提现：'.$result->desc,'withdraw-auto',$result->id);
        }

        return true;
    }


    public function query_request($item)
    {
        $payment = app('wechat.payment');
        $result = $payment->transfer->queryBalanceOrder($item->partner_trade_no);

        Helpers::log('[query] out_trade_no:'.$item->out_trade_no.' result:'.json_encode($result),'bonuses');

        if ($result&&$result['return_code'] == "SUCCESS"&&$result['result_code'] == "SUCCESS"){

            $item->query_count +=1;
            $item->last_query_time =date('Y-m-d H:i:s');
            $item->err_code = $result['err_code'];
            $item->err_code_des = $result['err_code_des'];

            $item->status = $result['status'];
            $item->transfer_time = $result['transfer_time'];
            $item->payment_time = $item->transfer_time;
            $item->detail_id = $result['detail_id'];


            if ($item->status == "FAILED" && isset($result['reason'])){
                $item->reason = $result['reason'];
            }

            if (!$item->payment_no){
                $item->payment_no = $item->detail_id;
            }

            return $item->save();
        }

        return false;
    }
}
